package com.example.demo.controller;

import com.example.demo.entity.Furniture;
import com.example.demo.entity.Users;
import com.example.demo.service.FurnitureService;
import com.example.demo.util.JsonResult;
import com.example.demo.util.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;



import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/sys-furniture")
public class furnitureController {
    @Autowired
    FurnitureService furnitureService;
    @Autowired
    RedisTemplate redisTemplate;
    //分页查询public Furniture[] pageFurniture(int page, int size, String query)
    @GetMapping("/furniturelist")
    public JsonResult<Users<Furniture>> pageFurniture(@RequestParam("pagenum") int pageNum, @RequestParam("pagesize") int pageSize, @RequestParam("query")String query){
        log.info("成功了"+query);
        System.out.println(pageNum+pageSize);
        List<Furniture> furnitures = furnitureService.pageFurniture((pageNum - 1)*pageSize, pageSize, query);
        Users users=new Users<Furniture>();
        users.setUsers(furnitures);
        users.setTotal(furnitureService.searchFurniture(query));
        return new JsonResult<Users<Furniture>>(200,users);
    }
    //添加家具对象
    @PostMapping("/addfurniture")
    public JsonResult<String> addFurniture(@RequestBody Furniture furniture){
        log.info(furniture.toString());
        if (furniture.getPrice()==0||furniture.getName().equals("")||furniture.getImage().equals("")){
            throw new ServiceException("添加信息不能为空");
        }
        furniture.setStatus(0);
        Date date=new Date();
        furniture.setCreatedTime(date);
        furniture.setCreatedUser( (String) redisTemplate.opsForValue().get("username"));
        furniture.setModifiedTime(date);
        furniture.setModifiedUser( (String) redisTemplate.opsForValue().get("username"));
        log.info(furniture.toString());
        furnitureService.add(furniture);
        JsonResult result = new JsonResult<>(200,"家具信息添加成功");
        return result;
    }
    //修改家具状态
    @PutMapping("/changeStatus")
    public JsonResult<String> changeFurniture(@RequestBody Furniture furniture){
        String username =  (String) redisTemplate.opsForValue().get("username");
        furniture.setModifiedUser(username);
        furniture.setModifiedTime(new Date());
        furniture.setStatus(furniture.isStatu()==true?0:1);
        furnitureService.changeFurniture(furniture);
        return new JsonResult(200,"修改成功");
    }
}
